//
//  UIScrollView+KeyboardExtension.m
//  WBusiness
//
//  Created by huangzhen on 2017/2/7.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "UIScrollView+KeyboardExtension.h"
#import <objc/runtime.h>
#import "UIView+Layout.h"
#import <ReactiveCocoa.h>
#import "UtilsMacro.h"
@interface UIScrollView()
@property (nonatomic, assign) CGFloat originalHeight;
@end

@implementation UIScrollView (KeyboardExtension)

- (BOOL)autoFrameWhenKeyboardDisplayEnable {
    return [objc_getAssociatedObject(self, @selector(autoFrameWhenKeyboardDisplayEnable)) boolValue];
}

- (void)setAutoFrameWhenKeyboardDisplayEnable:(BOOL)autoFrameWhenKeyboardDisplayEnable {
    objc_setAssociatedObject(self, @selector(autoFrameWhenKeyboardDisplayEnable), @(autoFrameWhenKeyboardDisplayEnable), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    self.originalHeight = self.height;
    NSLog(@"%f",self.height);
    if (autoFrameWhenKeyboardDisplayEnable) {
        @weakify(self);
        [[[[NSNotificationCenter defaultCenter]rac_addObserverForName:UIKeyboardWillChangeFrameNotification object:nil]takeUntil:self.rac_willDeallocSignal]subscribeNext:^(NSNotification *x) {
            @strongify(self);
            NSDictionary *userInfo = x.userInfo;
            CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
            CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
            CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
            UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
            
            
            [UIView animateWithDuration:duration
                                  delay:0.0f
                                options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState)
                             animations:^{
                @strongify(self);
                if (endFrame.origin.y == ScreenHeight) {
                    self.height = self.originalHeight;
                }else if (beginFrame.origin.y) {
                self.height = ScreenHeight-NavBarHeight - endFrame.size.height+KeyBoardInputAccessoryViewSpec;
                    
                }
            } completion:nil];

        }];
    }else {
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    }
}


- (CGFloat)originalHeight {
    return [objc_getAssociatedObject(self, @selector(originalHeight)) floatValue];
}

- (void)setOriginalHeight:(CGFloat)originalHeight {
    objc_setAssociatedObject(self, @selector(originalHeight), @(originalHeight), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
